package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.*;
import java.net.*;
import java.util.List;
import java.util.concurrent.*;

public class Service {


    private Mapper mapper;
    private int port;
    private ClassLoader classLoader;

    public Service(int port, Mapper mapper) {
        this.mapper = mapper;
        this.port = port;
        try {
            URL url = new File(mapper.getAppBase()).toURL();
            System.out.println("load class from url " + url);
            this.classLoader = new URLClassLoader(new URL[]{url});
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 启动 Service
     */
    public void start() throws IOException {
        loadServlet();

        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );




        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);





        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while(true) {

            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,mapper);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }
    }


    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet() {
        String path = mapper.getAppBase() + File.separator + "web.xml";
        System.out.println("load config from " + path);
        File file = new File(path);
//        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(path);

        try {
            InputStream resourceAsStream = new FileInputStream(file);
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                HttpServlet instance = (HttpServlet) classLoader.loadClass(servletClass).newInstance();
//                HttpServlet instance = (HttpServlet) Class.forName(File.separator + servletClass).newInstance();
                mapper.addWrapper(new Mapper.Wrapper(urlPattern, instance));
//                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());
            }



        } catch (DocumentException | IllegalAccessException
                | InstantiationException | ClassNotFoundException | FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}
